from flask import Blueprint, request
from models import Chat
from openai_api import get_responses_GPT
from extension import db
from sqlalchemy import func

gpt_bp = Blueprint('gpt', __name__)


@gpt_bp.route('ask', methods=['POST'])
def ask():
    question = request.json.get('question')
    #0:new,1:exist
    message = request.json.get('message')
    username = request.json.get('username')
    #new时不需要，exist时需要
    chatId = request.json.get('chatId')

    promptQuestion = question
    if message == 0:
        response = get_responses_GPT(promptQuestion, histories=[])
        if response:
            max_chatId = db.session.query(func.max(Chat.chatId)).filter_by(username=username).scalar()
            if max_chatId is None:
                max_chatId = -1
            #chatId最小为0
            newChat = Chat(chatId=max_chatId + 1, username=username, order=0, question=promptQuestion, answer=response)
            db.session.add(newChat)
            db.session.commit()
            return {
                "code": "0",
                "message": "SUCCESS",
                "data": {
                    "response": response,
                    "chatId": max_chatId + 1
                }
            }
        else:
            return {
                "code": "1",
                "message": "ERROR",
                "data": {
                    "response": "连接失败，请检查网络连接"
                }
            }
    else:
        #message为1,表示exist
        chats = Chat.query.filter_by(username=username, chatId=chatId).order_by(Chat.order).all()
        max_order = db.session.query(func.max(Chat.order)).filter_by(username=username, chatId=chatId).scalar()
        print("maxOrder")
        print(max_order)
        histories = []
        for chat in chats:
            histories.append({"role": "user", "content": chat.question})
            histories.append({"role": "assistant", "content": chat.answer})
        response = get_responses_GPT(promptQuestion, histories)
        if response:
            newChat = Chat(username=username, chatId=chatId, order=max_order + 1, question=question, answer=response)
            db.session.add(newChat)
            db.session.commit()
            return {
                "code": "0",
                "message": "SUCCESS",
                "data": {
                    "response": response
                }
            }
        else:
            return {
                "code": "1",
                "message": "ERROR",
                "data": {
                    "response": "连接失败，请检查网络连接"
                }
            }


@gpt_bp.route('histories', methods=['GET'])
def chat():
    username = request.args.get('username')
    chatId = request.args.get('chatId')
    chats = Chat.query.filter_by(username=username, chatId=chatId).order_by(Chat.order).all()
    if chats:
        resultList = []
        for chatResult in chats:
            resultList.append({
                "question": chatResult.question,
                "answer": chatResult.answer,
                "order": chatResult.order
            })
        return {
            "code": "0",
            "message": "SUCCESS",
            "data": resultList
        }


@gpt_bp.route('listAnswer/<string:username>')
def listAnswer(username):
    chats = Chat.query.filter_by(username=username, order=1).order_by(Chat.chatId).all()
    prompt = "你是一个博览群书的智者，请从古今中外的经典文学名著，为我解决下面的问题："
    if chats:
        resultList = []
        for chatResult in chats:
            resultList.append({
                "firstQuestion": chatResult.question,
                "chatId": chatResult.chatId
            })
        return {
            "code": "0",
            "message": "SUCCESS",
            "data": resultList
        }
    else:
        return {
            "code": "1",
            "message": "ERROR",
            "data": "未查询到该用户的对话记录"
        }